"use client";

import { useState } from "react";
import { Button } from "~/components/ui/button";
import { migrateDocumentType } from "~/app/_actions/migrate";

export default function MigrationPage() {
  const [result, setResult] = useState<{
    success?: boolean;
    message?: string;
    error?: string;
  } | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  const handleMigrate = async () => {
    try {
      setIsLoading(true);
      const migrationResult = await migrateDocumentType();
      setResult(migrationResult);
    } catch (error) {
      setResult({
        success: false,
        message: "执行迁移时出错",
        error: error instanceof Error ? error.message : String(error),
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="container mx-auto p-8">
      <h1 className="mb-6 text-3xl font-bold">数据库迁移管理</h1>
      
      <div className="mb-8 rounded-lg border border-gray-200 bg-white p-6 shadow-md dark:border-gray-700 dark:bg-gray-800">
        <h2 className="mb-4 text-xl font-semibold">文档类型字段迁移</h2>
        <p className="mb-4 text-gray-600 dark:text-gray-300">
          此迁移将向documents表添加document_type字段，并更新主键为包含document_type的复合主键。
          这将支持存储不同类型的专业技术文档。
        </p>
        
        <Button 
          onClick={handleMigrate} 
          disabled={isLoading}
          className="bg-blue-600 hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-800"
        >
          {isLoading ? "执行中..." : "执行迁移"}
        </Button>
        
        {result && (
          <div className={`mt-4 rounded-md p-4 ${
            result.success 
              ? "bg-green-50 text-green-800 dark:bg-green-900/30 dark:text-green-400" 
              : "bg-red-50 text-red-800 dark:bg-red-900/30 dark:text-red-400"
          }`}>
            <p className="font-medium">{result.message}</p>
            {result.error && <p className="mt-2 text-sm">{result.error}</p>}
          </div>
        )}
      </div>
      
      <div className="rounded-lg border border-yellow-200 bg-yellow-50 p-4 dark:border-yellow-700 dark:bg-yellow-900/30">
        <h3 className="mb-2 font-semibold text-yellow-800 dark:text-yellow-400">注意事项</h3>
        <ul className="list-inside list-disc text-yellow-700 dark:text-yellow-300">
          <li>迁移操作不可逆，请确保在执行前备份数据库。</li>
          <li>此页面仅供管理员使用，请勿向公众开放。</li>
          <li>迁移完成后，请更新相关代码以支持新的数据结构。</li>
        </ul>
      </div>
    </div>
  );
} 